
package com.myFwk.config.mybatisplus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Date;

/**
 * @Title: 当我们修改数据时，要添加一个修改人和修改时间
 * @Description: 实现 当我们新增数据时，要添加一个创建人、创建时间、修改时间，自动填充
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/9/2
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
public class AutoFilHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject, "lastUpdateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", Long.class, userId);
        this.strictInsertFill(metaObject, "created", Date.class, new Date());
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject, "lastUpdateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "modifyBy", Long.class, userId);
    }

    private Long getUserId() {
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        if (StringUtils.isNotBlank(userId)) {
            return Long.valueOf(userId);
        }
        return null;
    }

}
